// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

function randomSplice(num) {
  if (num > this.length) return []
  for(let i = 0; i < num; i++) {
      const rd = Math.round(Math.random() * (this.length - 1))
      this.splice(rd, 1)
  }
  return this
}

Array.prototype.randomSplice = randomSplice

// 云函数入口函数
exports.main = async (event, context) => {
  const openid = cloud.getWXContext().OPENID
  // 存我的单词
  let list = []

  const myWords = await db.collection('words').where({
    uploader: openid
  }).get()

  const fakeAnswers = await db.collection('fakeans').get()
  // 保证在10个
  list = myWords.data.length > 10 ? myWords.data.randomSplice(myWords.data.length - 10) : myWords.data

  const subjects = []

  list.forEach(l => {
    const subject = {
      list: [
        {id: 0, sign: 'A', mean: '', correct: false},
        {id: 1, sign: 'B', mean: '', correct: false},
        {id: 2, sign: 'C', mean: '', correct: false},
        {id: 3, sign: 'D', mean: '', correct: false},
      ]
    }
    // 先取到题干
    subject.spell = l.spell
    const corretIndex = Math.round(Math.random() * 3)
    for(const key in l.meaning) {
      subject.list[corretIndex].mean += `${key}${l.meaning[key].toString()} `
    }
    subject.list[corretIndex].correct = true
    
    for(let i = 0; i < 4 ;i ++) {
      if (i === corretIndex) continue
      const rdn = Math.round(Math.random() * (fakeAnswers.data.length - 1))
      subject.list[i].mean += fakeAnswers.data[rdn].text
    }

    subjects.push(subject)
  })

  return subjects
}